var express = require("express");
var router = express.Router();
var log4js = require('log4js');
var logger = log4js.getLogger();

// 微信预发货订单
router.get("/wxPrepay", function(request, response) {
    logger.info("/recharge/wxPrepay");
    var rechargeService = require('../../app/domain/services/rechargeService');
    rechargeService.handleWXPrepay(request, function(result){
        logger.info("handleWXPrepay res: %s to client.", JSON.stringify(result));
        response.write(JSON.stringify(result));
        response.end();
    });
});

// 微信发货回调
router.post("/wxpayNotify", function(request, response) {
    logger.info("/recharge/wxpayNotify");
    var postData = '';
    request.setEncoding("utf8");
    request.on('data', function (chunk) {
        postData += chunk;
    });

    request.on('end', function () {
        var rechargeService = require('../../app/domain/services/rechargeService');
        rechargeService.handleWXPayCallback(postData, function(result){
            logger.info("wxpayNotify response to tencent: %s", result);
            response.write(result);
            response.end();
        });
    });
});

// 玩一玩充值
router.post("/wywrecharge", function(request, response) {
    logger.info("/recharge/wywrecharge");
    var postData = '';
    request.setEncoding("utf8");
    request.on('data', function (chunk) {
        postData += chunk;
    });

    request.on('end', function () {
        var rechargeService = require('../../app/domain/services/rechargeService');
        rechargeService.handleWyxPay(JSON.parse(postData), function(result){
            result = (result == null) ? {resultCode : 0, msg : "充值成功"} : result;
            logger.info("wywrecharge response to: %s", JSON.stringify(result));
            response.write(JSON.stringify(result));
            response.end();
        });
    });
});

// 盛付通充值
router.post("/shengfuRecharge", function(request, response) {
    logger.info("/recharge/shengfuRecharge");
    let postData = '';
    request.setEncoding("utf8");
    request.on('data', function (chunk) {
        postData += chunk;
    });

    request.on('end', function () {
        let rechargeService = require('../../app/domain/services/rechargeService');
        rechargeService.handleShengfuRecharge(postData, function(result){
            logger.info("handleShengfuRecharge res: %s to client.", JSON.stringify(result));
            response.write(JSON.stringify(result));
            response.end();
        });
    });
});

module.exports = router;